﻿using AutoMapper;
using HamcoWcs.Contract.ContractCommon;
using HamcoWcs.DAL;
using HamcoWcs.Entitys.PlayBacks;
using HamcoWcs.Models.Common;
using HamcoWcs.Models.Monitors;
using HamcoWcs.Models.PlayBacks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace HamcoWcs.Main.Controllers.Common
{
    /// <summary>
    /// 回放控制器
    /// </summary>
    //[ApiExplorerSettings(IgnoreApi = true)]
    public class PlayBackController : BasicController
    {
        /// <summary>
        /// 获取回放数据
        /// </summary>
        [HttpPost]
        public async Task<IActionResult> GetPlayBackData(PlayBackQueryModel query)
        {
 
            DateTime date;
            try
            {
                date = query.FormatJSTimeStamp();
            }
            catch (Exception)
            {
                AddSystemLog("UI时间解析失败");
                return Json(ForeEndResult.Fail("时间解析失败"));
            }

            try
            {
                var a = Playback_Buffer.TryGetValue(date.ToString("yyyyMMddHHmmss"), out string data);

                MonitorData monitorData = null;
                if (a)
                {
                    monitorData = JsonConvert.DeserializeObject<MonitorData>(data);
                }

               
                
                return Json(new ForeEndResult(monitorData));
            }
            catch (PlayBackException ex)
            {
                //return Json(ForeEndResult.Fail(ex.Message));
                return Json(ForeEndResult.Ok);
            }
            catch (Exception ex)
            {
                AddSystemLog(ex.Message);
                return UnknownExceptionResult();
            }
        }

        [HttpPost]
        public IActionResult SetPlayBackZone(PlayBackTimeZone model)
        {
            try
            {
                var ll = new List<string>();
                var sw = Stopwatch.StartNew();
                List<string> datas = new List<string>();
                for (DateTime i = model.StartTime; i <= model.EndTime; i = i.AddHours(1))
                {
                    datas.Add(i.ToString("yyyyMMddHH"));
                }

                var files = Directory.GetFiles(_playbackLogFolder);
                var needlogfiles = files.Where(x => datas.Contains(Path.GetFileName(x)));
                var logStrs = new List<string>();
                foreach (var file in needlogfiles)
                {
                    logStrs.AddRange(System.IO.File.ReadAllLines(file));
                }

                sw.Stop();
                ll.Add($"1用时：{sw.ElapsedMilliseconds} ms");

                sw.Restart();
                Playback_Buffer.Clear();
                GC.Collect();

                foreach (var item in logStrs)
                {
                    var k = item[..14];
                    if (Playback_Buffer.ContainsKey(k)) continue;
                    var d = item[15..];

                    //var data = JsonConvert.DeserializeObject<MonitorData>(d);
                    Playback_Buffer.Add(k, d);
                }

                sw.Stop();
                ll.Add($"2用时：{sw.ElapsedMilliseconds} ms");

                logStrs.Clear();
                logStrs = null;
                GC.Collect();

                return Ok(new ForeEndResult()
                {
                    Details = string.Join(", ", ll)
                });
            }
            catch (PlayBackException ex)
            {
                return Json(ForeEndResult.Ok);
            }
            catch (Exception ex)
            {
                AddSystemLog(ex.Message);
                return UnknownExceptionResult();
            }
        }




        /// <summary>
        /// 结束回放
        /// </summary>
        [HttpPost]
        public IActionResult TurnOffPlayback([FromHeader] string userName = "")
        {
            try
            {
                //Console.WriteLine($"{userName} TurnOffPlayback");
                _currentUser = "";
                return Json(ForeEndResult.Ok);
            }
            catch (Exception ex)
            {
                AddSystemLog(ex.Message);
                return UnknownExceptionResult();
            }
        }


        /// <summary>
        /// 打开回放
        /// </summary>
        [HttpPost]
        public IActionResult OpenPlayback([FromHeader] string userName = "")
        {
            try
            {
                var now = DateTime.Now;
                if (string.IsNullOrEmpty(_currentUser))
                {
                    _currentUser = userName;
                    _setCurrentUser = DateTime.Now;
                    return Json(ForeEndResult.Ok);
                }
                if (userName == _currentUser)
                {
                    _currentUser = userName;
                    _setCurrentUser = DateTime.Now;
                    return Json(ForeEndResult.Ok);
                }
                if (now.AddSeconds(-10) > _setCurrentUser)
                {
                    _currentUser = userName;
                    _setCurrentUser = DateTime.Now;
                    return Json(ForeEndResult.Ok);
                }

                return Json(ForeEndResult.Fail($"{_currentUser}在回放中"));
            }
            catch (Exception ex)
            {
                AddSystemLog(ex.Message);
                return UnknownExceptionResult();
            }
        }

        [HttpPost]
        public IActionResult PlayBackHold([FromHeader] string userName = "")
        {
            try
            {
                if (userName != _currentUser)
                {
                    return Json(new ForeEndResult("error"));
                    throw new Exception();
                }
                _setCurrentUser = DateTime.Now;
                return Json(ForeEndResult.Ok);
            }
            catch (Exception)
            {
                return UnknownExceptionResult();
            }
            
        }

        private static string _currentUser = "";
        private static DateTime _setCurrentUser = DateTime.Now;
        //private static string LastPlayBack = new List<PlayBack>();
        //private static List<PlayBack> PLAYBACK_BUFFER = new List<PlayBack>();
        private static Dictionary<string, string> Playback_Buffer = new Dictionary<string, string>();

        /// <summary>
        /// 
        /// </summary>
        public override string ControllerName => "PlayBackController";

        /// <summary>
        /// 构造器
        /// </summary>
        public PlayBackController(WcsDbContext wcsDbContext, IMapper mapper, ILoggerService loggerService)
           : base(loggerService, mapper, wcsDbContext)
        {
        }

        static string _playbackLogFolder;
        static PlayBackController()
        {
            _playbackLogFolder = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "logs", "playback_logs");
        }
    }
}
